package com.xyebank.ledger.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;


public class DecryptEncryptUtil
{
//你好
  private static final String Algorithm = "DESede";
  //解密
  public static String decrypt3DES(String value, String key)
    throws Exception
  {
	  
    byte[] b = decryptMode(GetKeyBytes(key), Base64.decodeBase64(value));
    return new String(b,"utf-8");
  }
//加密
  public static String encrypt3DES(String value, String key)
    throws Exception
  {
    String str = byte2Base64(encryptMode(GetKeyBytes(key), value.getBytes("utf-8")));
    return str;
  }

  public static byte[] GetKeyBytes(String strKey)
    throws Exception
  {
    if ((null == strKey) || (strKey.length() < 1)) {
      throw new Exception("key is null or empty!");
    }
    //SHA(Secure Hash Algorithm，安全散列算法）
    MessageDigest alg = MessageDigest.getInstance("MD5");
    alg.update(strKey.getBytes());
    byte[] bkey = alg.digest();

    int start = bkey.length;
    byte[] bkey24 = new byte[24];
    for (int i = 0; i < start; i++) {
      bkey24[i] = bkey[i];
    }
    for (int i = start; i < 24; i++) {
      bkey24[i] = bkey[(i - start)];
    }
    return bkey24;
  }

  public static byte[] encryptMode(byte[] keybyte, byte[] src) throws Exception{
      SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
      Cipher c1 = Cipher.getInstance("DESede");
      c1.init(1, deskey);
      return c1.doFinal(src);

  }

  public static byte[] decryptMode(byte[] keybyte, byte[] src) throws Exception{

      SecretKey deskey = new SecretKeySpec(keybyte, "DESede");
      
      Cipher c1 = Cipher.getInstance("DESede");
      c1.init(2, deskey);
      return c1.doFinal(src);

  }
  
  public static String byte2Base64(byte[] b)
  {
    return Base64.encodeBase64String(b);
  }
  
  public static void main(String args[]){
	  try {
		String result = encrypt3DES("15528180702$2017-05-04 10:41:04$1000$12$100$100$10$10$20$20$2018-05-04 10:41:04$2500$3261703060000069", "5c0252c2c1c60de2936dba69d78c4fe0") + System.getProperty("line.separator");
		System.out.println(result);
	} catch (Exception e) {
		e.printStackTrace();
	}
  }
}
